﻿using System;
using System.Collections;
using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
using UnityEngine.Playables;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    public class PlayVideo : LatentActionNodeBase
    {
        [RequiredField]
        public BBParameter<string> videoName;
        public BBParameter<float> stopTime;
        
        [HideInInspector]
        public FlowOutput onStart;
        [HideInInspector]
        public FlowOutput onPreStart;
        [HideInInspector]
        public FlowOutput onStop;
        
        private bool stopped = false;

        public override bool allowRoutineQueueing { get { return false; } }
        
        public IEnumerator Invoke()
        {
            stopped = false;
            BlueprintUtils.PlayVideo(videoName.value, OnStopped);
            if (stopTime.value > 0.01)
            {
                yield return new WaitForSeconds(stopTime.value);
                try
                {
                    //BlueprintUtils.StopTimeline(videoName.value);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            else
            {
                yield return new UnityEngine.WaitUntil(() =>
                {
                    return stopped;
                });
            }
        }
        
        private void OnStart(PlayableDirector director)
        {
            onStart?.Call(new Flow());
        }

        private void OnPreStart()
        {
            onPreStart?.Call(new Flow());
        }

        private void OnStopped(PlayableDirector director)
        {
            onStop?.Call(new Flow());
            stopped = true;
        }

        protected override void OnRegisterDerivedPorts(FlowNode node)
        {
            onPreStart = node.AddFlowOutput("onPrePlay");
            onStart = node.AddFlowOutput("onPlay");
            onStop = node.AddFlowOutput("onStop");
            
            node.AddFlowInput("In", (f) => { Begin(Invoke(), f); });
            
        }
    }
}